<template>
    <view class="filter-page flex-col">

        <text class="text_8">组织类型</text>
        <view class="group_6 flex-row">
            <view class="text-wrapper flex-col" v-for="(option, index) in orgTypes" :key="index"
                :class="{ 'selected': form.orgType === option.value }" @click="selectOption('orgType', option.value)">
                <text class="text_label">{{ option.label }}</text>
            </view>
        </view>
        <view class="group_7 flex-col"></view>
        <text class="text_8">活动状态</text>
        <view class="group_6 flex-row">
            <view class="text-wrapper flex-col" v-for="(option, index) in activityStatus" :key="index"
                :class="{ 'selected': form.actStatus === option.value }"
                @click="selectOption('actStatus', option.value)">
                <text class="text_label">{{ option.label }}</text>
            </view>
        </view>
        <view class="group_7 flex-col"></view>
        <!-- 引入tagList组件 -->
        <text class="text_8">活动类型</text>
        <TagList :key="tagListKey" :initialSelectedLabels="form.labels" :tagData="tagCategories" :loading="tagLoading"
            :filterCategories="['爱好', '爱去']" @selected-labels-change="handleSelectedLabelsChange" />

        <view class="group_21 flex-row justify-between">
            <view class="text-wrapper_24 flex-col" @click="resetFilters">
                <text class="text_33">重置</text>
            </view>
            <view class="text-wrapper_25 flex-col" @click="saveFilters">
                <text class="text_34">保存筛选项</text>
            </view>
        </view>
    </view>
</template>
<script>
import TagList from '@/components/tagList/index.vue'
import { saveActFilter, deleteActFilter, myActFilter } from '@/common/api_meethuangshi.js'
export default {
    components: {
        TagList
    },
    data() {
        return {
            // 表单数据对象
            form: {
                userId: '',
                orgType: 0,
                actStatus: 0,
                tagId: '',
                labels: [] // 已选择的标签

            },
            // 性别选项
            orgTypes: [
                { label: '不限', value: 0 },
                { label: '企业', value: 1 },
                { label: '个人', value: 2 },
            ],
            activityStatus: [
                { label: '不限', value: 0 },
                { label: '报名中', value: 1 },
                { label: '已结束', value: 2 },
            ],
            userId: '',
            constants: {},
            tagListKey: 0, // 用于强制TagList组件重新渲染
            tagCategories: [], // 标签数据
            tagLoading: false, // 标签数据加载状态
            tagError: null // 标签数据加载错误
        };
    },
    async created() {
        this.userId = await this.getUserId()
        console.log(this.userId, 'this.userId')
        this.form.userId = this.userId
        if (!this.userId) {
            console.log('用户信息获取失败或用户未登录')
            return
        }
        this.fetchTagCategories(this.userId);

    },
    onLoad() {
    },
    methods: {
        // 处理来自TagList组件的选中标签变化
        handleSelectedLabelsChange(selectedLabels) {
            this.form.labels = selectedLabels
            console.log('父组件接收到选中标签变化:', this.form.labels)
        },
        // 统一的选项选择方法
        selectOption(type, value) {
            // 如果已选中相同值，则取消选择
            this.form[type] = this.form[type] === value ? '' : value
            console.log(`选中${type}:`, this.form[type], value)
        },
        // 重置筛选条件
        async resetFilters() {
            this.form = {
                userId: '',
                orgType: 0,
                actStatus: 0,
                tagId: '',
                labels: [] // 已选择的标签
            }
            this.tagListKey++ // 强制TagList组件重新渲染
            console.log(this.userId, '重置筛选条件')
            const res = await deleteActFilter(this.userId)
            console.log(res, 'deleteActFilter')
            this.$emit('updateList')
        },
        // 保存筛选条件并传递给父组件
        async saveFilters() {
            // 克隆表单数据，避免引用传递问题
            if (this.form.labels?.length) {
                this.form.tagId = this.form.labels.map(item => item.id).join(',')
            } else {
                this.form.tagId = ''
            }
            this.form.userId = this.userId
            const filterData = JSON.parse(JSON.stringify(this.form))

            console.log('保存筛选条件:', filterData)


            const res = await saveActFilter(filterData)
            if (res.code == 200) {
                uni.showToast({
                    title: '筛选条件已保存',
                    icon: 'success'
                })
                this.$emit('updateList')
            }


            // 可以添加成功提示
            uni.showToast({
                title: '筛选条件已保存',
                icon: 'success'
            })
        },
        // 获取标签数据
        async fetchTagCategories(id = '') {
            this.tagLoading = true;
            this.tagError = null;
            try {
                const res = await myActFilter(id);
                console.log('获取标签数据:', res);
                if (res.code === 200 && res.data) {
                    // 确保数据是数组格式并过滤无效数据
                    // this.form = res.data
                    const rawData = Array.isArray(res.data.tagList) ? res.data.tagList : [];
                    this.tagCategories = this.filterValidCategories(rawData);
                    console.log('过滤后的标签数据:', this.tagCategories);
                } else {
                    this.tagCategories = []; // 确保失败时也设置为空数组
                    this.tagError = res.message || '标签加载失败';
                }
            } catch (error) {
                console.error('获取标签列表失败:', error);
                this.tagCategories = []; // 确保异常时也设置为空数组
                this.tagError = '标签加载失败';
                uni.showToast({
                    title: '标签加载失败',
                    icon: 'none'
                });
            } finally {
                this.tagLoading = false;
            }
        },
        // 过滤有效的分类数据
        filterValidCategories(categories) {
            if (!Array.isArray(categories)) {
                return [];
            }
            return categories.filter(category => {
                if (!category || typeof category !== 'object') {
                    return false;
                }
                // 确保分类有基本信息
                if (!category.tagName || typeof category.tagName !== 'string') {
                    return false;
                }
                // 如果有子标签，过滤子标签
                if (category.sonTagObj) {
                    category.sonTagObj = this.getValidTags(category.sonTagObj);
                }
                return true;
            });
        },
        // 过滤有效的标签数据
        getValidTags(sonTagObj) {
            if (!Array.isArray(sonTagObj)) {
                return [];
            }
            return sonTagObj.filter(tag => {
                return tag &&
                    typeof tag === 'object' &&
                    tag.tagName &&
                    typeof tag.tagName === 'string' &&
                    tag.tagName.trim() !== '';
            });
        }
    }
};
</script>
<style lang="scss" scoped>
@import '../../static/style/common.css';

.filter-page {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 99999;
    background-color: rgba(247, 246, 255, 1);
    width: 100vw;
    height: 100vh;
    padding: 24px 16px 72px 16px;
    box-sizing: border-box;
    overflow-y: auto;

    .text-group_1 {
        .text_3 {
            overflow-wrap: break-word;
            color: rgba(52, 49, 79, 1);
            font-size: 16px;
            font-family: PingFangSC-Medium;
            font-weight: 500;
            text-align: left;
            white-space: nowrap;
            line-height: 22px;
        }
    }

    .slider-bar {
        // margin: 12px 0 24px 0;
    }

    .text_8 {
        overflow-wrap: break-word;
        color: rgba(52, 49, 79, 1);
        font-size: 16px;
        font-family: PingFangSC-Medium;
        font-weight: 500;
        text-align: left;
        white-space: nowrap;
        line-height: 22px;
        margin: 24px 0 0 0;
    }

    .group_6 {
        width: 100%;
        margin: 12px 0 0 0;
        gap: 8px;

        .text-wrapper {
            background-color: rgba(52, 49, 79, 0.06);
            border-radius: 14px;
            padding: 8px 20px 8px 20px;

            .text_label {
                overflow-wrap: break-word;
                color: rgba(52, 49, 79, 1);
                font-size: 14px;
                font-weight: normal;
                text-align: left;
                white-space: nowrap;
                line-height: 20px;
            }
        }
    }

    .group_7 {
        background-color: rgba(52, 49, 79, 0.08);
        width: 374px;
        height: 1px;
        margin: 16px 0 0 10px;
    }

    .text_12 {
        overflow-wrap: break-word;
        color: rgba(52, 49, 79, 1);
        font-size: 16px;
        font-family: PingFangSC-Medium;
        font-weight: 500;
        text-align: left;
        white-space: nowrap;
        line-height: 22px;
        margin: 24px 0 0 0;
    }

    .group_8 {
        margin: 12px 0 0 0;
        gap: 8px;

        .text-wrapper {
            background-color: rgba(52, 49, 79, 0.06);
            border-radius: 14px;
            padding: 8px 20px 8px 20px;

            .text_label {
                overflow-wrap: break-word;
                color: rgba(52, 49, 79, 1);
                font-size: 14px;
                font-weight: normal;
                text-align: left;
                white-space: nowrap;
                line-height: 20px;
            }
        }
    }

    // 为性别选择和认证情况添加选中样式，与TagList组件保持一致
    .group_6,
    .group_8 {
        .text-wrapper.selected {
            background: linear-gradient(141deg, rgba(238, 165, 247, 1), rgba(49, 158, 255, 1));
            border-radius: 14px;
            position: relative;
            z-index: 1;
            cursor: pointer;

            &::before {
                content: '';
                position: absolute;
                top: 2px;
                left: 2px;
                right: 2px;
                bottom: 2px;
                background: #FFFFFF;
                border-radius: 12px;
                z-index: -1;
            }

            .text_label {
                color: #319EFF;
                position: relative;
                z-index: 1;
            }
        }
    }

    .group_9 {
        background-color: rgba(52, 49, 79, 0.08);
        height: 1px;
        margin: 15px 0 0 0;
    }



    .group_21 {
        position: fixed;
        left: 0;
        bottom: 0;
        width: 100%;
        background: #F7F6FF;
        padding: 12px 16px;

        .text-wrapper_24 {
            border-radius: 20px;
            padding: 13px 51px 13px 51px;
            background: rgba(52, 49, 79, 0.06);

            .text_33 {
                overflow-wrap: break-word;
                color: rgba(52, 49, 79, 1);
                font-size: 16px;
                font-family: PingFangSC-Semibold;
                font-weight: 600;
                text-align: left;
                white-space: nowrap;
                line-height: 22px;
            }
        }

        .text-wrapper_25 {
            background: linear-gradient(173deg, #FFA5F5 0%, #319EFF 100%);
            border-radius: 20px;
            padding: 13px 65px 13px 65px;

            .text_34 {
                overflow-wrap: break-word;
                color: rgba(255, 255, 255, 1);
                font-size: 16px;
                font-family: PingFangSC-Semibold;
                font-weight: 600;
                text-align: right;
                white-space: nowrap;
                line-height: 22px;
            }
        }
    }
}
</style>